package com.sunfeng.chap5;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 *  ServerSocketChannel的accept方法返回的是selectChannel的子类,可用于注册到选择器中实现IO多路复用
 *
 *
 */
public class Test1_Server4 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress("localhost", 8888));
        SocketChannel socketChannel = serverSocketChannel.accept();
        // 汉字UTF-8 编码占三个字节   GBK占2个字节
        ByteBuffer byteBuffer = ByteBuffer.allocate(3);

        int read = socketChannel.read(byteBuffer);

        while (read != -1) {
            String string = new String(byteBuffer.array());
            System.out.println(string);
            // 将limit的值设置为position
            byteBuffer.flip();
            read= socketChannel.read(byteBuffer);
        }
        socketChannel.close();
        serverSocketChannel.close();

    }
}
